<?php
/**
 * Created by PhpStorm.
 * User: Baiyan
 * Date: 2018/4/5
 * Time: 18:26
 */

namespace src\ApiHelper;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use src\Exceptions\OperateFailedException;

trait ApiRequest
{
    /**
     * 模拟发送请求
     * @param $requestType
     * @param $url
     * @param array $params
     * @return mixed
     * @throws OperateFailedException
     */
    public static function sendRequest($requestType, $url, $params = null)
    {
        try{
            $client = new Client();
            if (isset($params)) {
                $result = $client->request($requestType, $url, $params);
            } else {
                $result = $client->request($requestType, $url);
            }
        } catch (GuzzleException $e) {
            throw new OperateFailedException('request|send request failed|msg:' . $e->getMessage() . '|params:' . json_encode($params) . '|result:' . json_encode($result));
        }
        return json_decode($result->getBody(),true);
    }
}
